package com.wasion.pwportable.handler;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.webkit.WebView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.activity.PwPortableActivity;
import com.wasion.pwportable.domain.vo.DeviceNode;
import com.wasion.pwportable.protocol.Protocol;
import com.wasion.pwportable.usb.F232DeviceManager;

public class USBDeviceHandler extends Handler {

	// 设备通信状态
	private static final int MSG_SUCCESS = 1;// 通信成功的标识
	private static final int MSG_FAILURE = 0;// 通信失败的标识
	private static final int RUNNING = 2; // 通信进行中

	// 上下文
	private Context context;

	// webview，浏览器窗口
	private WebView webView;

	// Google的Json转换工具
	private Gson gson = new Gson();

	protected Message msg2;

	// 上一次的模块地址
	public static String LAST_COMM_ADDR = "";

	public USBDeviceHandler(Context context) {
		this.context = context;
		this.webView = PwPortableActivity.getWebView();
	}

	public void getDeviceInfo() {

		new Thread(new Runnable() {
			public void run() {

				Message msg1 = USBDeviceHandler.this.obtainMessage();
				msg1.what = RUNNING;
				msg1.sendToTarget();

				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				String deviceInfo = getDeviceInfoJson();
				if (deviceInfo == null) {
					Message msg2 = USBDeviceHandler.this.obtainMessage();
					msg2.what = MSG_FAILURE;
					msg2.sendToTarget();
				} else {
					Message msg3 = USBDeviceHandler.this.obtainMessage();
					msg3.what = MSG_SUCCESS;
					msg3.obj = deviceInfo;
					msg3.sendToTarget();
				}
			}
		}).start();
	}

	public String getDeviceInfoJson() {

		F232DeviceManager usbDevice = F232DeviceManager.getInstance(context);

		DeviceNode node;

		try {
			node = usbDevice.getDeviceInformation();

			if (!"disableId".equals(node.getId())) {

				// usbDevice.disconnect();
				if (usbDevice.connect()) {
					usbDevice.setConfig();

					String commAddr = usbDevice.getDeiveCommAddr();
					if (StringUtil.isEmpty(commAddr)) {
						setDisable(node);
					} else {
						node.setStatus("1"); // 模块可用
						node.setCommAddr(commAddr);

						// 地址可能错误，重新读取一次
						if (!StringUtil.isEmpty(LAST_COMM_ADDR)
								&& !LAST_COMM_ADDR.equals(commAddr)) {

							commAddr = usbDevice.getDeiveCommAddr();
							node = usbDevice.getDeviceInformation();
							node.setStatus("1"); // 模块可用
							node.setCommAddr(commAddr);
						}

						// 读模块地址时 添加到Protocol里面
						Protocol.SENDERID = Protocol.toRealAddress(commAddr);
						LAST_COMM_ADDR = commAddr;
					}
				} else {
					setDisable(node);
				}
			} else {
				setDisable(node);
			}

			return gson.toJson(node);

		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return null;
	}

	/**
	 * 
	 * @Title: setDisable
	 * @Description: 模块信息（不可用）
	 * @param
	 * @return
	 * @throws
	 */
	private void setDisable(DeviceNode node) {
		node.setName("No device!");
		node.setSerialNumber("");
		node.setId("disableId");
		node.setStatus("0"); // 模块不可用
		node.setCommAddr("");
	}

	@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);

		switch (msg.what) {
		case RUNNING:
			break;
		case MSG_SUCCESS:
			String deviceInfo = null;
			deviceInfo = msg.obj.toString();
			webView.loadUrl("javascript:getDeviceInfoCallback('" + deviceInfo
					+ "');window.debugjsi.isUSBAttached()");
			break;
		case MSG_FAILURE:
			Toast.makeText(context, "通信模块错误!", Toast.LENGTH_SHORT).show();
			break;
		}
	}
}